package javazuoye.one;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/06/26 23:39
 */
public class _2_2_7 {
    public static void main(String[] args) {
        List<Integer> l1 = Arrays.stream(new int[]{1, 2, 3, 4, 5, 6, 7}).boxed().collect(Collectors.toList());
        List<Integer> l2 = Arrays.stream(new int[]{1, 2, 3, 4, 4, 5, 6, 7}).boxed().collect(Collectors.toList());
        System.out.println("并集："+bing(new ArrayList<>(l1), new ArrayList<>(l2)));
        System.out.println("差集："+cha(new ArrayList<>(l1), new ArrayList<>(l2)));
        System.out.println("交集："+jiao(new ArrayList<>(l1), new ArrayList<>(l2)));
    }

    public static List<Integer> bing(List<Integer> l1, List<Integer> l2) {
        l1.addAll(l2);
        l1.sort(Comparator.comparingInt(o -> o));
        return l1;
    }

    public static List<Integer> cha(List<Integer> l1, List<Integer> l2) {
        int i1 = 0, i2 = 0;
        while (is_legal(l1, l2, i1, i2)) {
            while (is_legal(l1, l2, i1, i2) && i2 < l2.size() && l1.get(i1).equals(l2.get(i2))) {
                l1.remove(i1);
                l2.remove(i2);
            }
            while (is_legal(l1, l2, i1, i2) && l1.get(i1) < l2.get(i2)) {
                i1++;
            }
            while (is_legal(l1, l2, i1, i2) && l1.get(i1) > l2.get(i2)) {
                i2++;
            }
        }
        return bing(l1, l2);
    }

    public static List<Integer> jiao(List<Integer> l1, List<Integer> l2) {
        int i1 = 0, i2 = 0;
        while (is_legal(l1, l2, i1, i2)) {
            while (is_legal(l1, l2, i1, i2) && l1.get(i1).equals(l2.get(i2))) {
                i1++;
                i2++;
            }
            while (is_legal(l1, l2, i1, i2) && l1.get(i1) < l2.get(i2)) {
                l1.remove(i1);
            }
            while (is_legal(l1, l2, i1, i2) && l1.get(i1) > l2.get(i2)) {
                l2.remove(i2);
            }
        }
        return l1.size() < l2.size() ? l1 : l2;
    }

    public static boolean is_legal(List<Integer> l1, List<Integer> l2, int i1, int i2) {
        return i1 < l1.size() && i2 < l2.size();
    }
}
